import { ref, reactive, watch, UnwrapNestedRefs } from 'vue'
import app from '@/app'
import axios from '@/axios'
import Project from './types/Project'

interface ProjCache {
    current: Project,
    /**
     * 尝试从缓存中获取一个项目，如果force设置为true，则强制获取新值。
     * @param id 项目的ID，如果该ID和缓存中的ID相同，则调取缓存
     * @param force 是否强制获取新值
     */
    getProj (id : string, force? : boolean) : Promise<Project>,
    /**
     * 从缓存中获取项目
     */
    clearCache (id? : string) : void,
    /**
     * 跳向 查看 界面。在此界面中，有修改权限的用户可以修改项目的基本信息
     * @param id 项目的ID
     * @param force 是否强制清除缓存加载，建议设为true
     * @param newWindow 是否在新闻页面里打开
     */
    toDetailPage(id : string, force : boolean, newWindow : boolean) : void,
    /**
     * 跳向 修改 界面。在此界面中，有修改权限的用户可以修改整个申报书
     * @param id 项目的ID
     * @param force 是否强制清除缓存加载，建议设为true
     * @param newWindow 是否在新闻页面里打开
     */
    toEditPage(id : string, force : boolean, newWindow : boolean) : void,
}

export const cache : ProjCache = reactive({
    current: Project.getEmptyProject(),
    timestamp: Date.now(),
    clearCache (id? : string) {
        if (!id || id === this.current.basicInfo.ID) {
            Object.assign(this.current, Project.getEmptyProject());
        }
    },
    async getProj (id : string, force = false) : Promise<Project> {
        if (this.current.basicInfo.ID === id && !force && Date.now() - this.timestamp < 1000 * 60 * 5) {
            console.log("load from cache: " + id)
            let {promise, resolve} = app.withResolvers<Project>();
            resolve(this.current);
            return promise;
        }

        let msg : any = await axios.post("/api/proj/common/GetProj", { id });

        if (!msg.success) {
            this.clearCache()
            this.current.failMsg = msg.msg;
            return this.current;
        }

        this.timestamp = Date.now();
        this.current = Project.fromGetProjResponse(msg);
        return this.current;
    },    
    toDetailPage(id : string, force : boolean, newWindow : boolean) : void {
        if (!app.router) {
            return;
        }

        if (force) this.clearCache();

        const url = "/manage/innov/detail";
        if (newWindow) {
            const uri = app.router.resolve({
                path: url,
                query: {
                    id
                }
            });
            window.open(uri.fullPath);
        } else {
            app.toPage({
                path: url,
                query: {
                    id
                }
            });
        }
    },
    toEditPage(id : string, force : boolean, newWindow : boolean) : void {
        if (!app.router) {
            return;
        }

        if (force) this.clearCache();

        const url = "/manage/proj/editor";
        if (newWindow) {
            const uri = app.router.resolve({
                path: url,
                query: {
                    id
                }
            });
            window.open(uri.fullPath);
        } else {
            app.toPage({
                path: url,
                query: {
                    id
                }
            });
        }
    },
});

export function useEmptyData () {
    let empty = Project.getEmptyProject();
    empty.basicInfo.ProjectType = "创新训练";
    return reactive(empty)
};

export function useEmptyBasicInfo () {
    let empty = Project.getEmptyProject();
    return reactive(empty.basicInfo);
}

export default cache;